package co.th.bjc.md.helper;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import co.th.bjc.md.common.ConnectDB;
import co.th.bjc.md.model.ImpRating;

public class IMPRatingHelper {

	private static Logger _log = Logger.getLogger(IMPRatingHelper.class);
	
	public List<ImpRating> findAllImpRating() throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		List<ImpRating> listImpRating = new ArrayList<ImpRating>(0);
		ConnectDB connectDB = null;
		try{
			String sql = "SELECT * FROM imp_rating";
			_log.info("SQL : " + sql);
			
			connectDB = new ConnectDB();
			conn = connectDB.getConnection();
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			while (rs.next()){
				listImpRating.add(this.setImpRating(rs));
			}
		}catch(Exception ex){
			_log.error("findAllRegion --> " + ex.toString());
			ex.printStackTrace();
		}finally{
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			connectDB.close();
		}
		return listImpRating;
	}
	
	public ImpRating findImpRatingByImpCode(BigDecimal impCode) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		ImpRating imp = null;
		ConnectDB connectDB = null;
		try{
			String sql = "SELECT * FROM imp_rating WHERE imp_code = ?";
			_log.info("SQL : " + sql);
			
			connectDB = new ConnectDB();
			conn = connectDB.getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setBigDecimal(1, impCode);
			
			rs = stmt.executeQuery();
			if (rs.next()){
				imp = this.setImpRating(rs);
			}
		}catch(Exception ex){
			_log.error("findImpRatingByImpCode --> " + ex.toString());
			ex.printStackTrace();
		}finally{
			if (rs != null) rs.close();
			if (stmt != null) stmt.close();
			connectDB.close();
		}
		return imp;
	}
	
	private ImpRating setImpRating(ResultSet rs) throws Exception{
		ImpRating imp = new ImpRating();
		imp.setImpCode(rs.getBigDecimal("imp_code"));
		imp.setImpName(rs.getString("imp_name"));
		imp.setCreateBy(rs.getString("create_by"));
		imp.setCreateDate(rs.getDate("create_date"));
		imp.setUpdateBy(rs.getString("update_by"));
		imp.setUpdateDate(rs.getDate("update_date"));
		return imp;
	}
}
